import wanlshop_config from './config/config';
import Api from '@/common/globe.js';

export const requestTask = (url, data = {}, method = 'get', isLoding = false, type = 'json') => {
    if (isLoding) {
        uni.showLoading({
            title: '加载中...',
            mask: true
        });
    }
    const token = uni.getStorageSync('token');
    let urlText = wanlshop_config.appurl + url;

    return new Promise((resolve, reject) => {
        uni.request({
            url: urlText,
            method: method,
            data: data,
            header: {
                token
            },
            dataType: type,
            success: function (res) {
                if (isLoding) uni.hideLoading();
                if (res.statusCode === 200) {
                    if (type !== 'json') {
                        resolve(res.data);
                    } else {
                        if (res.data.code === 1) {
                            resolve(res.data.data);
                            return;
                        }

                        Api.msg(res.data.msg);
                    }
                    return;
                }
                if (res.statusCode === 401) {
                    // Api.msg('请登录');
                    uni.removeStorageSync('token');
                    Api.authRedirectTo('/pages/login/login');
                    return;
                }
                if (typeof res.data == 'string') {
                    Api.msg(JSON.parse(res.data).msg);
                    return;
                }
                Api.msg(res.data.msg);
            },
            fail: function (res) {
                console.log(res);
                if (isLoding) uni.hideLoading();
            }
        });
    });
};

/**
 * 上传图片
 * */
export function uploadFile(filePath, formData) {
    let option = {};
    option.url = wanlshop_config.appurl + `/common/upload`;
    option.name = 'file';
    option.filePath = filePath || '';
    option.formData = {};
    option.timeout = 10000;

    let token = uni.getStorageSync('token');
    if (token) {
        (option.header = {}).token = token;
    }

    return new Promise((resolve, reject) => {
        uni.showLoading({ title: '上传中' });
        uni.uploadFile({
            ...option,
            success: (res) => {
                uni.hideLoading();
                if (res.statusCode === 200 && JSON.parse(res.data).code === 1) {
                    resolve(JSON.parse(res.data).data);
                } else {
                    uni.showToast({
                        title: JSON.parse(res.data).msg || '文件上传失败!',
                        icon: 'error',
                        duration: 2000
                    });

                    let pages = getCurrentPages();
                    console.error(`文件上传错误\nurl: ${option.url}\npage: ${pages[pages.length - 1].route},\nerrMsg: ${JSON.stringify(res.data)}`);

                    reject(JSON.parse(res.data));
                }
            },
            fail: (err) => {
                uni.hideLoading();
                if (err.errMsg.trim() == 'uploadFile:fail createUploadTask:fail network is down') {
                    uni.showToast({
                        title: '请求失败，请检查网络是否通畅',
                        icon: 'none',
                        duration: 2000
                    });
                }
                reject(err);
            }
        });
    });
}

/**
 * 选择上传图片
 * @param {object} [params] 可以选择的图片数量
 * @param {number} [params.count] 可以选择的图片数量
 * @param {'album'|'camera'} [params.sourceType] 图片来源是相册还是相机，默认二者都有
 * @param {'original'|'compressed'} [params.sizeType] 可以指定是原图还是压缩图，默认二者都有
 * @param {object} [options] 而外可选项
 * @param {number} [options.formData] 而外参数
 * @param {string} [options.url] 请求地址
 * @param {string} [options.name] 表单的项目名，默认为 file
 * @param {number} [options.timeout] 超时时间ms
 * async handleChooseImageUpload() {
				let image = []
				const result = await common.chooseImage(1).catch((err) => console.log("chooseImageErrMsg:", err));
				const suceessList = (result || []).filter((item) => item.isSuccess === true);
				if (suceessList.length > 0) {
					image = suceessList.map((item) => item.path)
					console.log(image)
				}
			},
 
 */
export function chooseImage(
    params = {
        count: 1,
        sourceType: ['album', 'camera'],
        sizeType: ['original', 'compressed']
    },
    options = {}
) {
    return new Promise((resolve, reject) => {
        uni.chooseImage({
            count: params.count || 1,
            sourceType: params.sourceType || ['album', 'camera'],
            sizeType: params.sizeType || ['original', 'compressed'],
            success: (chooseImageRes) => {
                console.log('✔ click: chooseImage > success');
                const tempFilePaths = chooseImageRes.tempFiles.map((item) => item.path);
                let total = tempFilePaths.length;
                let successList = [];
                let failList = [];
                tempFilePaths.forEach(async (item) => {
                    let res = await uploadFile(item, options).catch((err) => {
                        failList.push(item.path);
                        console.log('text', err);
                    });
                    console.log('✔ click: chooseImage: success > uploadFile: success');
                    console.log(res);

                    if (res) {
                        successList.push(res.fullurl);
                    }
                    if (successList.length + failList.length === total) {
                        console.log('✔ click: chooseImage: success > uploadFile: success > successList:max');
                        resolve([...successList.map((item) => ({ path: item, isSuccess: true })), ...failList.map((item) => ({ path: item, isSuccess: false }))]);
                    }
                });
            },
            fail: (err) => {
                console.log('❌ click: chooseImage > fail: ', err);
                reject([]);
            }
        });
    });
}
